/**
 * Notes: 资讯后台管理
 * Ver : CCMiniCloud Framework 2.0.1 ALL RIGHTS RESERVED BY cclinux0730 (wechat)
 * Date: 2021-07-11 07:48:00 
 */

const BaseProjectAdminService = require('./base_project_admin_service.js');
const AdminHomeService = require('../admin/admin_home_service.js');
const dataUtil = require('../../../../framework/utils/data_util.js');
const util = require('../../../../framework/utils/util.js');
const timeUtil = require('../../../../framework/utils/time_util.js');
const cloudUtil = require('../../../../framework/cloud/cloud_util.js');

const NewsModel = require('../../model/news_model.js');

class AdminNewsService extends BaseProjectAdminService {


	/**添加资讯 */
	async insertNews({
		title, 
		cateId, 
		cateName, 
		order, 
		status = 1, 
		forms
	}) {
		// 参数验证
		if (!title || title.length < 2 || title.length > 200) {
			this.AppError('资讯标题需在2-200字符之间');
		}
		if (!cateId || !cateName) {
			this.AppError('请选择资讯分类');
		}
		if (!forms || !Array.isArray(forms)) {
			this.AppError('请提交资讯内容表单');
		}

		// 构建数据对象
		const data = {
			NEWS_TITLE: title,
			NEWS_CATE_ID: cateId,
			NEWS_CATE_NAME: cateName,
			NEWS_ORDER: order || 0,
			NEWS_STATUS: status,
			NEWS_FORMS: forms,
			NEWS_OBJ: dataUtil.dbForms2Obj(forms),
			NEWS_ADD_TIME: timeUtil.time(),
			NEWS_EDIT_TIME: timeUtil.time(),
			_pid: this.getProjectId()
		};

		// 插入数据库
		const id = await NewsModel.insert(data);
		return { id, success: true };
	}

	/**删除资讯数据 */
	async delNews(id) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 删除资讯
		await NewsModel.del(id);
		return { success: true };
	}

	// 更新forms信息
	async updateNewsForms({
		id,
		hasImageForms
	}) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 更新表单
		await NewsModel.update(id, {
			NEWS_FORMS: hasImageForms,
			NEWS_OBJ: dataUtil.dbForms2Obj(hasImageForms),
			NEWS_EDIT_TIME: timeUtil.time()
		});
		return { success: true };
	}


	/**
	 * 更新富文本详细的内容及图片信息
	 * @returns 返回 urls数组 [url1, url2, url3, ...]
	 */
	async updateNewsContent({
		id,
		content // 富文本数组
	}) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 提取图片URL
		const urls = [];
		content.forEach(item => {
			if (item.type === 'image' && item.url) {
				urls.push(item.url);
			}
		});

		// 更新内容
		await NewsModel.update(id, {
			NEWS_CONTENT: content,
			NEWS_CONTENT_URLS: urls,
			NEWS_EDIT_TIME: timeUtil.time()
		});
		return { urls, success: true };
	}

	/**
	 * 更新资讯图片信息
	 * @returns 返回 urls数组 [url1, url2, url3, ...]
	 */
	async updateNewsPic({
		id,
		imgList // 图片数组
	}) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 更新图片
		await NewsModel.update(id, {
			NEWS_PIC: imgList,
			NEWS_EDIT_TIME: timeUtil.time()
		});
		return { success: true };
	}


	/**更新资讯数据 */
	async editNews({
		id,
		title,
		cateId,
		cateName,
		order,
		status,
		forms
	}) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 参数验证
		if (title && (title.length < 2 || title.length > 200)) {
			this.AppError('资讯标题需在2-200字符之间');
		}

		// 构建更新数据
		const data = {};
		if (title !== undefined) data.NEWS_TITLE = title;
		if (cateId !== undefined) data.NEWS_CATE_ID = cateId;
		if (cateName !== undefined) data.NEWS_CATE_NAME = cateName;
		if (order !== undefined) data.NEWS_ORDER = order;
		if (status !== undefined) data.NEWS_STATUS = status;
		if (forms !== undefined) {
			data.NEWS_FORMS = forms;
			data.NEWS_OBJ = dataUtil.dbForms2Obj(forms);
		}
		data.NEWS_EDIT_TIME = timeUtil.time();

		// 更新资讯
		await NewsModel.update(id, data);
		return { success: true };
	}

	/**修改资讯状态 */
	async statusNews(id, status) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 更新状态
		await NewsModel.update(id, {
			NEWS_STATUS: status,
			NEWS_EDIT_TIME: timeUtil.time()
		});
		return { success: true };
	}

	/**置顶与排序设定 */
	async sortNews(id, sort) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 更新排序
		await NewsModel.update(id, {
			NEWS_ORDER: sort,
			NEWS_EDIT_TIME: timeUtil.time()
		});
		return { success: true };
	}

	/**首页设定 */
	async vouchNews(id, vouch) {
		// 检查资讯是否存在
		const news = await NewsModel.getOne({ _id: id, _pid: this.getProjectId() });
		if (!news) {
			this.AppError('资讯不存在');
		}

		// 更新推荐状态
		await NewsModel.update(id, {
			NEWS_VOUCH: vouch ? 1 : 0,
			NEWS_EDIT_TIME: timeUtil.time()
		});
		return { success: true };
	}

	/**获取资讯信息 */
	async getNewsDetail(id) {
		let fields = '*';

		let where = {
			_id: id
		}
		let news = await NewsModel.getOne(where, fields);
		if (!news) return null;

		return news;
	}

	/**取得资讯分页列表 */
	async getAdminNewsList({
		search, // 搜索条件
		sortType, // 搜索菜单
		sortVal, // 搜索菜单
		orderBy, // 排序
		whereEx, //附加查询条件
		page,
		size,
		isTotal = true,
		oldTotal
	}) {

		orderBy = orderBy || {
			'NEWS_ORDER': 'asc',
			'NEWS_ADD_TIME': 'desc'
		};
		let fields = 'NEWS_TITLE,NEWS_DESC,NEWS_CATE_ID,NEWS_CATE_NAME,NEWS_EDIT_TIME,NEWS_ADD_TIME,NEWS_ORDER,NEWS_STATUS,NEWS_CATE2_NAME,NEWS_VOUCH,NEWS_QR,NEWS_OBJ';

		let where = {};
		where.and = {
			_pid: this.getProjectId() //复杂的查询在此处标注PID
		};

		if (util.isDefined(search) && search) {
			where.or = [
				{ NEWS_TITLE: ['like', search] },
			];

		} else if (sortType && util.isDefined(sortVal)) {
			// 搜索菜单
			switch (sortType) {
				case 'cateId': {
					where.and.NEWS_CATE_ID = String(sortVal);
					break;
				}
				case 'status': {
					where.and.NEWS_STATUS = Number(sortVal);
					break;
				}
				case 'vouch': {
					where.and.NEWS_VOUCH = 1;
					break;
				}
				case 'top': {
					where.and.NEWS_ORDER = 0;
					break;
				}
				case 'sort': {
					orderBy = this.fmtOrderBySort(sortVal, 'NEWS_ADD_TIME');
					break;
				}

			}
		}

		return await NewsModel.getList(where, fields, orderBy, page, size, isTotal, oldTotal);
	}
}

module.exports = AdminNewsService;